package com.weishi.project.sport.home.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.weishi.common.utils.SecurityUtils;
import com.weishi.common.utils.StringUtils;
import com.weishi.framework.security.LoginSport;
import com.weishi.framework.security.service.SysLoginService;
import com.weishi.framework.security.service.TokenService;
import com.weishi.framework.web.domain.AjaxResult;
import com.weishi.project.api.vo.LoginVo;
import com.weishi.project.sport.home.service.SportLoginService;
import com.weishi.project.training.domain.Sportsman;
import com.weishi.project.training.service.ISportsmanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * 运动员登录端接口实现类
 */
@Service
public class SportLoginServiceImpl implements SportLoginService {

    /**
     * 用户表接口
     */
    @Autowired
    private SysLoginService loginService;

    /**
     * 运动员表 接口
     */
    @Autowired
    private ISportsmanService sportsmanService;

    /**
     * token验证处理 接口
     */
    @Autowired
    private TokenService tokenService;



    /**
     * 运动员端登录
     */
    @Override
    public AjaxResult sportLogin(LoginVo login) {
        // 1，查询运动员是否存在
        Sportsman sportsman = sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getName , login.getUsername()));
        if(StringUtils.isNull(sportsman)){
            return AjaxResult.error("登录失败，没有此运动员！" );
        }

        // 判断密码是否正确
        if(SecurityUtils.matchesPassword(login.getPassword() , sportsman.getPassword()) == false){
            return AjaxResult.error("登录失败，密码错误！" );
        }

        LoginSport loginSport = new LoginSport();
        loginSport.setSportsman(sportsman);
        return AjaxResult.success("登录成功！" , tokenService.createToken(loginSport));
    }


    /**
     * 运动员端退出登录
     */
    @Override
    public AjaxResult sportLogout(HttpServletRequest request) {
        try {
            loginService.logout(request);
            return AjaxResult.success("退出登录成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.success("退出登录失败");
        }
    }


    /**
     * 运动员端 注册
     */
    @Override
    public AjaxResult register(Sportsman sportsman) {
        // 判断此用户是否已经注册
        Sportsman sportsmanName = sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getName , sportsman.getName()));
        if(StringUtils.isNotNull(sportsmanName)){
            return AjaxResult.error("此用户已经注册！" );
        }

        sportsman.setCtime(new Date());  //创建时间
        sportsman.setPassword(SecurityUtils.encryptPassword(sportsman.getPassword()));  //用户密码
        sportsmanService.save(sportsman);  //新增操作
        return AjaxResult.success();
    }







}
